package com.ericsson.web.xss.httponly;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HttpOnlyFilter implements Filter {
	private FilterConfig config;

	@Override
	public void destroy() {
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		Cookie[] cookies = ((HttpServletRequest)req).getCookies();
		Cookie sessionCookie = null;
		for(Cookie cookie : cookies) {
			if(cookie.getName().equals("JSESSIONID")) {
				sessionCookie = cookie;
			}
		}
		HttpOnlyResponseWrapper hres = new HttpOnlyResponseWrapper(
				(HttpServletResponse) res, sessionCookie);
		chain.doFilter(req, hres);
	}

	public FilterConfig getFilterConfig() {
		return this.config;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}
}